<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import {
  createStore,
  updateStore,
  updateStoreStatus,
  uploadStoreAvatar,
  getUserProfile, // 确保从index导入
  getStoreDetail, // 确保从index导入
} from "@/api/index";
import { Cropper, CircleStencil } from "vue-advanced-cropper";
import "vue-advanced-cropper/dist/style.css";
import { ElMessage, ElMessageBox } from "element-plus";
import { useMerchantStore } from "@/store";
import { Close } from "@element-plus/icons-vue";
import MerchantLayout from "@/components/merchant/MerchantLayout.vue";
import { StoreUpdateDTO } from "@/types/store";
import StarRating from "@/components/common/StarRating.vue";

const router = useRouter();
const merchantStore = useMerchantStore();

const userInfo = reactive({
  username: "",
  email: "",
  phone: "",
});
const loading = ref(false);
const statusLoading = ref(false);
const storeDialogVisible = ref(false);
const isEdit = ref(false);
const storeForm = reactive({
  id: "",
  name: "",
  address: "",
  phone: "",
  categoryId: null as number | null,
  categoryName: "",
  businessHours: "",
  description: "",
  status: "营业中",
  logo: "",
});

// 店铺分类列表
const storeCategories = ref<Array<{ id: number; name: string }>>([]);
const loadingCategories = ref(false);

// 获取店铺分类列表
const fetchStoreCategories = async () => {
  loadingCategories.value = true;
  try {
    // 使用公开API获取店铺分类列表
    const { getPublicStoreCategories } = await import("@/api/index");
    console.log("使用公开API获取店铺分类列表");

    const res = await getPublicStoreCategories();
    console.log("店铺分类列表响应:", res);

    // 处理响应数据
    let categoriesData;
    if (res.data?.data) {
      categoriesData = res.data.data;
    } else if (res.data) {
      categoriesData = res.data;
    } else {
      categoriesData = [];
    }

    storeCategories.value = Array.isArray(categoriesData) ? categoriesData : [];
    console.log("解析后的店铺分类列表:", storeCategories.value);
  } catch (error) {
    console.error("获取店铺分类列表失败:", error);
    ElMessage.error("获取店铺分类失败，请检查网络或联系管理员。");
  } finally {
    loadingCategories.value = false;
  }
};

const showCropper = ref(false);
const cropperImg = ref("");
const cropperRef = ref();

// 店铺头像上传校验+弹出裁剪
const beforeStoreLogoUpload = (file: File) => {
  const isImage = file.type.startsWith("image/");
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isImage) {
    ElMessage.error("只能上传图片文件！");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("图片大小不能超过5MB！");
    return false;
  }
  // 读取图片数据用于裁剪
  const reader = new FileReader();
  reader.onload = (e) => {
    cropperImg.value = e.target?.result as string;
    showCropper.value = true;
  };
  reader.readAsDataURL(file);
  // 阻止 el-upload 自动上传
  return false;
};

const handleStoreLogoUpload = async (option: any) => {
  const formData = new FormData();
  formData.append("file", option.file);
  try {
    const res = await uploadStoreAvatar(merchantStore.currentStoreId, formData);
    let url =
      typeof res.data === "string"
        ? res.data
        : res.data?.url || res.data?.data?.url || res.data?.data || res.data;
    if (typeof url === "object" && url !== null) {
      url = url.url || url.path || "";
    }
    if (typeof url !== "string" || !url) {
      ElMessage.error("头像上传失败，未获取到图片地址");
      return;
    }
    storeForm.logo = url;
    ElMessage.success("头像上传成功");
  } catch (e) {
    ElMessage.error("头像上传失败");
  }
};

const handleCrop = async () => {
  if (!cropperRef.value) return;
  const result = cropperRef.value.getResult();
  if (!result || !result.canvas) {
    ElMessage.error("裁剪失败，请重试");
    return;
  }
  result.canvas.toBlob(async (blob: Blob | null) => {
    if (!blob) return;
    const formData = new FormData();
    formData.append("file", blob, "logo.png");
    try {
      const res = await uploadStoreAvatar(
        merchantStore.currentStoreId,
        formData
      );
      let url =
        typeof res.data === "string"
          ? res.data
          : res.data?.url || res.data?.data?.url || res.data?.data || res.data;
      if (typeof url === "object" && url !== null) {
        url = url.url || url.path || "";
      }
      if (typeof url !== "string" || !url) {
        ElMessage.error("头像上传失败，未获取到图片地址");
        showCropper.value = false;
        return;
      }
      storeForm.logo = url;
      ElMessage.success("头像上传成功");
    } catch (e) {
      ElMessage.error("头像上传失败");
    }
    showCropper.value = false;
  }, "image/png");
};

const handleCropCancel = () => {
  showCropper.value = false;
};

const fetchUserInfo = async () => {
  loading.value = true;
  try {
    // 获取商家账号信息
    try {
      const userRes = await getUserProfile();
      const user = userRes.data?.data || userRes.data;
      userInfo.username = user?.username || "";
      userInfo.email = user?.email || "";
      userInfo.phone = user?.phone || "";
    } catch {}

    // 获取店铺列表
    await merchantStore.fetchStores();
  } catch {}
  loading.value = false;
};

const handleStoreChange = (id: string) => {
  merchantStore.setCurrentStore(id);
};

const openAddStore = () => {
  isEdit.value = false;
  Object.assign(storeForm, {
    id: "",
    name: "",
    address: "",
    phone: "",
    categoryId: null,
    categoryName: "",
    businessHours: "",
    description: "",
    status: "营业中",
  });
  storeDialogVisible.value = true;
};

const openEditStore = () => {
  isEdit.value = true;
  // 深拷贝店铺信息，避免直接修改store中的数据
  const storeData = JSON.parse(JSON.stringify(merchantStore.currentStore));

  // 设置表单数据
  storeForm.id = storeData.id || "";
  storeForm.name = storeData.name || "";
  storeForm.address = storeData.address || "";
  storeForm.phone = storeData.phone || "";
  storeForm.categoryId = storeData.categoryId || null;
  storeForm.categoryName = storeData.categoryName || storeData.category || "";
  storeForm.businessHours = storeData.businessHours || "";
  storeForm.description = storeData.description || "";
  storeForm.logo = storeData.logo || "";

  console.log("编辑前的店铺信息:", storeForm);

  // 将API状态值转换为前端状态值
  if (storeData.status === "OPEN") {
    storeForm.status = "营业中";
  } else if (storeData.status === "CLOSED") {
    storeForm.status = "已关闭";
  }

  storeDialogVisible.value = true;
};

// 刷新店铺信息
const refreshStoreInfo = async () => {
  loading.value = true;
  try {
    // 获取店铺列表
    await merchantStore.fetchStores();

    // 如果有当前选中的店铺，直接从API获取最新信息
    if (merchantStore.currentStoreId) {
      try {
        const response = await getStoreDetail(merchantStore.currentStoreId);
        const storeData = response.data?.data || response.data;

        console.log("API返回的店铺详情:", storeData);

        if (storeData) {
          // 处理店铺分类信息
          if (storeData.categoryId && storeCategories.value.length > 0) {
            const category = storeCategories.value.find(
              (c) => c.id === parseInt(storeData.categoryId)
            );
            if (category) {
              storeData.categoryName = category.name;
              console.log("找到匹配的分类:", category.name);
            } else {
              console.log("未找到匹配的分类ID:", storeData.categoryId);
              // 尝试重新获取分类列表
              await fetchStoreCategories();
              const categoryAfterFetch = storeCategories.value.find(
                (c) => c.id === parseInt(storeData.categoryId)
              );
              if (categoryAfterFetch) {
                storeData.categoryName = categoryAfterFetch.name;
                console.log(
                  "重新获取后找到匹配的分类:",
                  categoryAfterFetch.name
                );
              }
            }
          } else {
            console.log("店铺没有分类ID或分类列表为空");
          }

          // 更新store中的信息
          merchantStore.storeInfo = { ...storeData };

          // 更新stores数组中对应的店铺信息
          const storeIndex = merchantStore.stores.findIndex(
            (s) => s.id === merchantStore.currentStoreId
          );
          if (storeIndex !== -1) {
            merchantStore.stores[storeIndex] = { ...storeData };
          }

          console.log("已从API直接获取最新店铺信息:", merchantStore.storeInfo);
        }
      } catch (error) {
        console.error("直接获取店铺信息失败:", error);
        // 如果直接获取失败，回退到使用store中的方法
        merchantStore.setCurrentStore(merchantStore.currentStoreId);
      }
    }
  } catch (error) {
    console.error("刷新店铺信息失败", error);
  } finally {
    loading.value = false;
  }
};

const handleSaveStore = async () => {
  try {
    // 创建一个新对象，而不是直接使用storeForm引用
    const storeData = { ...storeForm };

    // 确保所有字段都有值，即使是空字符串
    for (const key in storeData) {
      if (storeData[key] === null || storeData[key] === undefined) {
        if (key !== "categoryId") {
          // 除了categoryId，其他字段设为空字符串
          storeData[key] = "";
        }
      }
    }

    // 创建一个新对象，只包含需要的字段
    const apiData: any = {
      name: storeData.name,
      logo: storeData.logo,
      description: storeData.description,
      phone: storeData.phone,
      address: storeData.address,
      businessHours: storeData.businessHours,
    };

    // 如果有分类ID，则添加到请求中
    if (storeData.categoryId !== null && storeData.categoryId !== undefined) {
      apiData.categoryId = storeData.categoryId;

      // 确保有对应的分类名称
      if (!storeData.categoryName) {
        const categoryIdValue =
          typeof storeData.categoryId === "string"
            ? parseInt(storeData.categoryId)
            : storeData.categoryId;

        const category = storeCategories.value.find(
          (c) => c.id === categoryIdValue
        );
        if (category) {
          storeData.categoryName = category.name;
          console.log("保存前设置分类名称:", category.name);
        }
      }
    }

    console.log("API请求数据:", apiData);

    if (isEdit.value) {
      console.log("更新店铺信息:", apiData);
      await updateStore(storeData.id, apiData);
      ElMessage.success("店铺信息已更新");
    } else {
      console.log("创建店铺:", apiData);
      await createStore(apiData);
      ElMessage.success("店铺已创建");
    }
    storeDialogVisible.value = false;

    // 刷新店铺信息
    await refreshStoreInfo();
  } catch (error) {
    console.error("保存店铺信息失败:", error);
    ElMessage.error("操作失败");
  }
};

const handleStatusChange = async (val: string, isManual = false) => {
  console.log("handleStatusChange 被调用，val:", val);
  if (!merchantStore.currentStoreId) {
    ElMessage.warning("请先选择一个店铺。");
    return;
  }

  statusLoading.value = true;
  try {
    if (
      merchantStore.storeInfo.status === "PENDING" ||
      merchantStore.storeInfo.status === "SUSPENDED"
    ) {
      ElMessage.warning("当前店铺状态不允许更改营业状态。");
      return;
    }

    // 将前端状态值转换为API需要的状态值
    const apiStatus = val === "open" ? "OPEN" : "CLOSED";
    console.log(
      "尝试更新店铺状态:",
      merchantStore.currentStoreId,
      "到",
      apiStatus
    );

    // 调用API更新状态 - 尝试多种可能的参数名称
    await updateStoreStatus(merchantStore.currentStoreId, {
      status: apiStatus,
      storeStatus: apiStatus,
      state: apiStatus,
    });

    // 直接更新本地状态，设置suppressNotification为false，避免显示重复消息
    merchantStore.updateStoreStatus(apiStatus, true);

    // 直接在这里显示消息，而不是通过store显示
    ElMessage.success(
      `店铺已${apiStatus === "OPEN" ? "开启营业" : "关闭营业"}`
    );
  } catch (error) {
    console.error("更新店铺状态失败:", error);
    ElMessage.error("状态更新失败");

    // 恢复UI状态
    await refreshStoreInfo();
  } finally {
    statusLoading.value = false;
  }
};

// 处理分类变更
const handleCategoryChange = (categoryId: number) => {
  console.log(
    "分类变更，ID:",
    categoryId,
    "当前分类列表:",
    storeCategories.value
  );

  // 根据选中的分类ID找到对应的分类名称
  const selectedCategory = storeCategories.value.find(
    (c) => c.id === categoryId || c.id === parseInt(categoryId.toString())
  );

  if (selectedCategory) {
    storeForm.categoryName = selectedCategory.name;
    console.log("找到匹配的分类:", selectedCategory.name);
  } else {
    storeForm.categoryName = "";
    console.log("未找到匹配的分类");

    // 如果没有找到匹配的分类，尝试重新获取分类列表
    fetchStoreCategories().then(() => {
      const categoryAfterFetch = storeCategories.value.find(
        (c) => c.id === categoryId || c.id === parseInt(categoryId.toString())
      );
      if (categoryAfterFetch) {
        storeForm.categoryName = categoryAfterFetch.name;
        console.log("重新获取后找到匹配的分类:", categoryAfterFetch.name);
      }
    });
  }
};

onMounted(async () => {
  await fetchUserInfo();
  await fetchStoreCategories();

  // 调试：打印店铺和分类信息
  console.log("=== 店铺和分类信息调试 ===");
  console.log("当前店铺信息:", merchantStore.storeInfo);
  console.log("当前店铺分类ID:", merchantStore.storeInfo.categoryId);
  console.log("分类列表:", storeCategories.value);

  // 尝试匹配分类
  if (merchantStore.storeInfo.categoryId && storeCategories.value.length > 0) {
    const categoryId =
      typeof merchantStore.storeInfo.categoryId === "string"
        ? parseInt(merchantStore.storeInfo.categoryId)
        : merchantStore.storeInfo.categoryId;

    const matchedCategory = storeCategories.value.find(
      (c) => c.id === categoryId
    );
    console.log("匹配的分类:", matchedCategory);

    if (matchedCategory) {
      console.log("应该显示的分类名称:", matchedCategory.name);
      // 直接更新分类名称
      merchantStore.storeInfo.categoryName = matchedCategory.name;
    }
  }
});
</script>

<template>
  <merchant-layout>
    <div class="store-view">
      <el-card class="store-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>店铺管理</span>
            <el-button
              type="primary"
              size="small"
              @click="openAddStore"
              style="margin-left: 12px"
              >新增店铺</el-button
            >
          </div>
        </template>
        <div style="margin-bottom: 18px">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="账号">{{
              userInfo.username
            }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{
              userInfo.email
            }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{
              userInfo.phone
            }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <!-- 店铺选择元素已移除，页面还原为仅店铺管理内容 -->
        <el-button
          size="small"
          style="margin: 12px 0 0 0"
          @click="openEditStore"
          :disabled="!merchantStore.currentStoreId"
          >编辑店铺</el-button
        >
        <el-descriptions
          :column="2"
          border
          v-loading="loading || merchantStore.loading"
          style="margin-top: 18px"
        >
          <el-descriptions-item label="店铺名称">
            <el-avatar
              v-if="merchantStore.storeInfo.logo"
              :src="merchantStore.storeInfo.logo"
              :size="32"
              style="margin-right: 8px; vertical-align: middle"
            />
            {{ merchantStore.storeInfo.name }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag
              :type="
                merchantStore.storeInfo.status === 'OPEN' ? 'success' : 'info'
              "
              effect="light"
              style="margin-right: 10px"
            >
              {{
                merchantStore.storeInfo.status === "OPEN" ? "营业中" : "已关闭"
              }}
            </el-tag>
            <el-switch
              v-model="merchantStore.storeInfo.status"
              :loading="statusLoading"
              active-value="OPEN"
              inactive-value="CLOSED"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="
                (val) =>
                  handleStatusChange(val === 'OPEN' ? 'open' : 'closed', true)
              "
              :disabled="
                merchantStore.storeInfo.status === 'PENDING' ||
                merchantStore.storeInfo.status === 'SUSPENDED'
              "
            />
          </el-descriptions-item>
          <el-descriptions-item label="地址">{{
            merchantStore.storeInfo.address
          }}</el-descriptions-item>
          <el-descriptions-item label="电话">{{
            merchantStore.storeInfo.phone
          }}</el-descriptions-item>
          <el-descriptions-item label="分类">{{
            merchantStore.storeInfo.categoryName || "未设置"
          }}</el-descriptions-item>
          <el-descriptions-item label="营业时间">{{
            merchantStore.storeInfo.businessHours
          }}</el-descriptions-item>
          <el-descriptions-item label="简介" :span="2">{{
            merchantStore.storeInfo.description
          }}</el-descriptions-item>
          <el-descriptions-item label="评分" :span="2">
            <star-rating
              :score="merchantStore.storeInfo.rating"
              :precision="1"
            />
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      <el-dialog v-model="storeDialogVisible" width="420px" :show-close="false">
        <template #header>
          <div class="custom-dialog-header">
            <span>{{ isEdit ? "编辑店铺" : "新增店铺" }}</span>
            <button
              class="custom-close-btn"
              @click="storeDialogVisible = false"
              aria-label="关闭"
            >
              <el-icon><Close /></el-icon>
            </button>
          </div>
        </template>
        <el-form :model="storeForm" label-width="80px">
          <el-form-item label="店铺头像">
            <el-upload
              class="store-logo-uploader"
              action=""
              :show-file-list="false"
              :before-upload="beforeStoreLogoUpload"
              :http-request="handleStoreLogoUpload"
            >
              <el-avatar
                v-if="storeForm.logo"
                :src="storeForm.logo"
                :size="56"
                style="margin-bottom: 6px"
              />
              <el-button size="small" style="margin-top: 6px"
                >上传头像</el-button
              >
            </el-upload>
          </el-form-item>
          <!-- 裁剪弹窗 -->
          <el-dialog
            v-model="showCropper"
            title="裁剪店铺头像"
            width="400px"
            :close-on-click-modal="false"
            :show-close="false"
          >
            <template #header>
              <div class="custom-dialog-header">
                <span>裁剪店铺头像</span>
                <button
                  class="custom-close-btn"
                  @click="showCropper = false"
                  aria-label="关闭"
                >
                  <el-icon><Close /></el-icon>
                </button>
              </div>
            </template>
            <div
              style="display: flex; flex-direction: column; align-items: center"
            >
              <Cropper
                ref="cropperRef"
                :src="cropperImg"
                :stencil-component="CircleStencil"
                :stencil-props="{ aspectRatio: 1 }"
                :autoZoom="true"
                :resizeImage="true"
                :imageRestriction="'stencil'"
                style="width: 300px; height: 300px; background: #f5f5f5"
              />
              <div style="margin-top: 16px">
                <el-button type="primary" @click="handleCrop"
                  >裁剪并上传</el-button
                >
                <el-button @click="handleCropCancel">取消</el-button>
              </div>
            </div>
          </el-dialog>
          <el-form-item label="店铺名称">
            <el-input v-model="storeForm.name" />
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="storeForm.address" />
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="storeForm.phone" />
          </el-form-item>
          <el-form-item label="分类">
            <el-select
              v-model="storeForm.categoryId"
              placeholder="请选择店铺分类"
              style="width: 100%"
              @change="handleCategoryChange"
            >
              <el-option
                v-for="category in storeCategories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="营业时间">
            <el-input v-model="storeForm.businessHours" />
          </el-form-item>
          <el-form-item label="简介">
            <el-input
              v-model="storeForm.description"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="storeDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveStore">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </merchant-layout>
</template>

<style scoped>
.store-view {
  padding: 32px;
}
.store-card {
  border-radius: 18px;
  background: #fffbe7;
  box-shadow: 0 2px 8px #ffd54f33;
}
.store-selector-bar {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  gap: 0.5rem;
  min-height: 32px;
}
.store-selector-label {
  width: 140px;
  font-size: 15px;
  color: #a05a1c;
  margin-right: 6px;
  font-weight: 500;
  text-align: right;
  line-height: 32px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex-shrink: 0;
}
.store-selector-select :deep(.el-input__wrapper) {
  min-height: 32px !important;
  height: 32px !important;
  font-size: 15px;
  align-items: center;
}
.store-selector-select :deep(.el-input__inner) {
  min-height: 32px !important;
  height: 32px !important;
  font-size: 15px;
  align-items: center;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.custom-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  padding-right: 4px;
}
.custom-close-btn {
  border: none;
  background: #f5f6fa;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.2s, box-shadow 0.2s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-left: 8px;
}
.custom-close-btn:hover {
  background: #ffd54f;
  color: #a05a1c;
  box-shadow: 0 4px 16px rgba(255, 213, 79, 0.15);
}
</style>
